package com.ruoyi.web.controller.task;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.task.domain.KwTaskInfo;
import com.ruoyi.task.service.IKwTaskInfoService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Service;
import java.util.List;

/**
 * 监控任务Controller
 * 
 * @author gonianer
 * @date 2023-11-17
 */
@RestController
@RequestMapping("/task/task")
public class KwTaskInfoController extends BaseController
{
    @Autowired
    private IKwTaskInfoService kwTaskInfoService;
    @Autowired
    private ISysJobService jobService;

    /**
     * 查询监控任务列表
     */
    @PreAuthorize("@ss.hasPermi('task:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(KwTaskInfo kwTaskInfo)
    {
        startPage();
        List<KwTaskInfo> list = kwTaskInfoService.selectKwTaskInfoList(kwTaskInfo);
        return getDataTable(list);
    }

    /**
     * 导出监控任务列表
     */
    @PreAuthorize("@ss.hasPermi('task:task:export')")
    @Log(title = "监控任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KwTaskInfo kwTaskInfo)
    {
        List<KwTaskInfo> list = kwTaskInfoService.selectKwTaskInfoList(kwTaskInfo);
        ExcelUtil<KwTaskInfo> util = new ExcelUtil<KwTaskInfo>(KwTaskInfo.class);
        util.exportExcel(response, list, "监控任务数据");
    }

    /**
     * 获取监控任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('task:task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(kwTaskInfoService.selectKwTaskInfoById(id));
    }

    @PreAuthorize("@ss.hasPermi('task:task:query')")
    @GetMapping(value = "/rollback/{id}")
    public AjaxResult rollback(@PathVariable("id") Integer id)
    {
        KwTaskInfo taskInfo = kwTaskInfoService.selectKwTaskInfoById(id);
        if(taskInfo==null){
            throw new ServiceException("任务Id="+id+"不存在");
        }
        String jobName = taskInfo.getTaskType();
        if(jobName.contains("Host")){
            //启动回滚主机任务
            try {
                SysJob job = new SysJob();
                job.setJobId(taskInfo.getJobId());
                job.setJobName("addHost");
                job.setJobGroup("sys");
                job.setInvokeTarget("hostTask.rollbackHost("+id+"L)");
                job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
                job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
                job.setCreateBy(getUsername());
                jobService.runOnce(job);
            } catch (SchedulerException | TaskException e) {
                throw new ServiceException("启动回滚任务Id="+id+"失败："+e.getMessage());
            }
        }else if(jobName.contains("Cluster")){
            //启动回滚主机任务
            try {
                SysJob job = new SysJob();
                job.setJobId(taskInfo.getJobId());
                job.setJobName("addCluster");
                job.setJobGroup("sys");
                job.setInvokeTarget("clusterTask.rollbackCluster("+id+"L)");
                job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
                job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
                job.setCreateBy(getUsername());
                jobService.runOnce(job);
            } catch (SchedulerException | TaskException e) {
                throw new ServiceException("启动回滚任务Id="+id+"失败："+e.getMessage());
            }
        }

        return success();
    }

    @PreAuthorize("@ss.hasPermi('task:task:query')")
    @GetMapping(value = "/retry/{id}")
    public AjaxResult retry(@PathVariable("id") Integer id)
    {
        KwTaskInfo taskInfo = kwTaskInfoService.selectKwTaskInfoById(id);
        if(taskInfo==null){
            throw new ServiceException("任务Id="+id+"不存在");
        }
        String jobName = taskInfo.getTaskType();
        if(jobName.contains("Host")){
            //启动回滚主机任务
            try {
                SysJob job = new SysJob();
                job.setJobId(taskInfo.getJobId());
                job.setJobName("addHost");
                job.setJobGroup("sys");
                job.setInvokeTarget("hostTask.retryAddHost("+id+"L)");
                job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
                job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
                job.setCreateBy(getUsername());
                jobService.runOnce(job);
            } catch (SchedulerException | TaskException e) {
                throw new ServiceException("启动重试任务Id="+id+"失败："+e.getMessage());
            }
        }else if(jobName.contains("Cluster")){
            //启动回滚主机任务
            try {
                SysJob job = new SysJob();
                job.setJobId(taskInfo.getJobId());
                job.setJobName("addCluster");
                job.setJobGroup("sys");
                job.setInvokeTarget("clusterTask.retryAddCluster("+id+"L)");
                job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
                job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
                job.setCreateBy(getUsername());
                jobService.runOnce(job);
            } catch (SchedulerException | TaskException e) {
                throw new ServiceException("启动回滚任务Id="+id+"失败："+e.getMessage());
            }
        }
        return success();
    }

    /**
     * 新增监控任务
     */
    @PreAuthorize("@ss.hasPermi('task:task:add')")
    @Log(title = "监控任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KwTaskInfo kwTaskInfo)
    {
        return toAjax(kwTaskInfoService.insertKwTaskInfo(kwTaskInfo));
    }

    /**
     * 修改监控任务
     */
    @PreAuthorize("@ss.hasPermi('task:task:edit')")
    @Log(title = "监控任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KwTaskInfo kwTaskInfo)
    {
        return toAjax(kwTaskInfoService.updateKwTaskInfo(kwTaskInfo));
    }

    /**
     * 删除监控任务
     */
    @PreAuthorize("@ss.hasPermi('task:task:remove')")
    @Log(title = "监控任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(kwTaskInfoService.deleteKwTaskInfoByIds(ids));
    }
}
